<template>
	<view class="page-container">
		<view class="header">
			<x-status-bar></x-status-bar>
			<view class="flex-center-between header-navbar">
				<x-back-btn></x-back-btn>
				<view class="u-f-40 common-title">{{ lang_order.confirmOrder }}</view>
				<view></view>
			</view>
		</view>

		<!-- 地址卡片 -->
		<view v-if="showAddress" style="padding: 22rpx 30rpx 0;">
			<view class="address-container flex-center-center">
				<view v-if="addressObj" class="flex-center-between" style="width: 100%;" @click="changeAddress()">
					<view>
						<view class="flex-center u-f-28 u-lh-40 color-grew">
							<view class="u-m-r-18">{{ addressObj.name || '' }}</view>
							<view>{{ addressObj.mobile || '' }}</view>
						</view>
						<view class="u-m-t-10 u-f-32 u-lh-44 font-medio">{{ formatAddress(addressObj) }}</view>
					</view>

					<u-icon name="right" custom-prefix="u" color="#ACACAC" size="28"></u-icon>
				</view>

				<view v-else class="flex-center-center">
					<x-common-btn width="292" height="64" color="#FF4C2F" borderColor="#FF4C2F" background="#FFFFFF"
						@click="changeAddress">
						<view>{{ lang_address.add }}</view>
					</x-common-btn>
				</view>

				<image src="@/static/image/common/order_address_line.png" style="width: 782rpx; height: 10rpx;"
					class="address-line"></image>
			</view>
		</view>

		<!-- 商品内容 -->
		<view style="padding: 24rpx 34rpx 0;">
			<view class="bg-white" style="padding: 24rpx 0 42rpx;border-radius: 16rpx;">
				<view v-if="merchantName" class="flex-center bg-white" style="width: 100%;padding: 30rpx 34rpx 0;">
					<image src="@/static/image/common/relation.png" style="width: 32rpx; height: 32rpx;"
						class="clear-flex"></image>

					<view class="u-m-l-6 linecamp-1">{{ merchantName }}</view>
				</view>

				<view>
					<view v-for="(item, index) in dataList" :key="index">
						<coupon-card v-if="[5, 7].includes(item.goodsType)" :item="({ ...item, couponType: 3, canBuy: false })"></coupon-card>
						<goods-card v-else :item="dealItem(item)"></goods-card>
						<u-gap height="1" bg-color="#f5f5f5"></u-gap>
					</view>
				</view>

				<view class="u-f-28 u-lh-40" style="padding: 0 24rpx 0 28rpx;">
					<!-- <view class="flex-center-between u-m-t-28">
						<view class="color-grew">数量</view>
						<u-number-box button-size="30"></u-number-box>
					</view> -->
					<view v-if="showAddress" class="flex-center-between u-m-t-28">
						<view class="color-grew">{{ lang_goods.postage }}</view>
						<view class="font-medio color-red">{{ lang_unit.money }}{{ freightCount.toFixed(2) }}</view>
					</view>
					<view class="flex u-m-t-28">
						<view class="color-grew clear-flex">{{ lang_goods.leaveMessage }}</view>

						<view class="textarea-container flex u-p-14 u-m-l-12">
							<textarea v-model="remark" :placeholder="lang_goods.leaveMessageTips" class="u-f-24"
								style="width: 100%;"></textarea>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 留空 -->
		<view style="height: 200rpx;"></view>

		<!-- 提交操作 -->
		<x-fixed-bottom>
			<view class="flex-center-between" style="padding: 40rpx 34rpx 28rpx;">
				<view class="flex flex-column">
					<view class="flex-baseline font-bold" style="color: #FF6011;">
						<view class="u-f-32 u-lh-32">{{ lang_unit.money }}</view>
						<view class="u-f-52 u-lh-52">{{ totalAmount }}</view>
					</view>

					<view class="u-f-28 u-lh-40 color-grew">{{ lang_goods.totalAmount }}</view>
				</view>

				<view>
					<x-common-btn width="226" height="82" @click="submitAction">
						<view class="u-f-32 u-lh-44 font-medio">{{ lang_order.submitOrder }}</view>
					</x-common-btn>
				</view>
			</view>
		</x-fixed-bottom>

		<x-pay-select v-model="selectVisible" :info="selectInfo" @change="changeSelect"></x-pay-select>
	</view>
</template>

<script>
	import {
		payAction
	} from '@/utils/pay.js'
	import {
		goodsFreight
	} from '@/api/user/goods.js'
	import {
		orderInfo,
		orderCreate,
		orderCreateCart,
		orderCreateCoupon
	} from '@/api/user/order.js'
	import {
		addressGetDefaultAddress
	} from '@/api/user/address.js'
	export default {
		data() {
			return {
				addressObj: null,
				remark: '',
				type: '',
				dataList: [],
				goodsIds: '',
				freightCount: 0,

				selectVisible: false,
				selectInfo: {},
				
				isClick: false,
			}
		},
		computed: {
			totalAmount() {
				let count = 0;
				this.dataList.map(item => {
					count = Number(count).add(Number(item.discountPrice || 0).mul(item.amount || 1))
				})
				count = Number(count).add(this.freightCount) || 0
				return Number(count).toFixed(2)
			},
			showAddress() {
				let list = this.dataList || []
				let includes = [5, 6, 7]
				let item = list.findIndex(item => includes.includes(item.goodsType)) > -1
				return list.length && !item
			},
			merchantName() {
				let { merchantName } = this.dataList[0] || {}
				return merchantName || 'Dondego'
			}
		},
		onLoad() {
			// 获取全局事件
			this.event = this.getOpenerEventChannel();
			this.event.on('order-ready', ({
				type,
				list
			}) => {
				this.dataList = list
				this.type = type
				this.goodsIds = list.map(item => item.goodsId).join(',')
				if (this.showAddress) {
					this.initAddress()
				}
			})
		},
		methods: {
			// 添加或修改收货地址
			changeAddress() {
				uni.navigateTo({
					url: `/pages/user/address/list/list?type=use`,
					events: {
						changeAction: e => {
							if (JSON.stringify(e) !== JSON.stringify(this.addressObj)) {
								this.addressObj = {
									...e
								}
								this.initGoodsFreight(e.id)
							}
						}
					},
					success: res => {
						res.eventChannel.emit('address-select', this.addressObj)
					}
				})
			},
			// 点击确定后
			changeSelect(type) {
				payAction(type, this.selectInfo.orderNumber).then(() => {
					this.selectVisible = false
					let [{
						goodsType,
					}] = this.dataList
					if ([5, 6, 7].includes(goodsType)) {
						this.jumpBack(2)
					}
				})
			},
			// 获取默认地址
			initAddress() {
				if (this.shopcartAddress.id) {
					this.addressObj = this.shopcartAddress
					this.initGoodsFreight(this.shopcartAddress.id)
				} else {
					addressGetDefaultAddress({}).then(result => {
						this.addressObj = result
						this.initGoodsFreight(result.id)
					})
				}
			},
			// 获取运费
			initGoodsFreight(addressId) {
				if (!addressId) return
				goodsFreight({
					addressId,
					goodsIds: this.goodsIds
				}).then((data) => {
					this.freightCount = data || 0
				})
			},
			dealItem(item) {
				let {
					discountPrice,
					finalPrice,
					stockSpecs,
					goodsName,
					specs,
					title,
					imgUrl,
					goodsImage
				} = item
				return ({
					...item,
					orderType: item.goodsType,
					discountPrice: discountPrice || finalPrice,
					specs: specs || stockSpecs,
					title: title || goodsName,
					imgUrl: imgUrl || goodsImage
				})
			},
			// 提交订单
			submitAction() {
				if (this.showAddress && !this.addressObj) {
					return this.$api.msg(this.lang_address.selectAddressTips)
				}
				let queryObj = { remark: this.remark };
				if (this.showAddress) {
					queryObj.addressId = this.addressObj.id
				}
				// 购物车多商品
				if (this.type === 'shopcart') {
					let cartIds = this.dataList.map(item => item.cartId).join(',')

					orderCreateCart({
						cartIds,
						...queryObj
					}).then((result) => {
						uni.redirectTo({
							url: `/pages/user/order/detail/detail?orderNumber=${ result }`
						})
					})
				} else {
					let [{
						goodsType,
						goodsId,
						pinId,
						amount: buyAmount,
						id: goodsSpecAttributePriceId
					}] = this.dataList
					queryObj = {
						...queryObj,
						goodsId,
						buyAmount: buyAmount || 1
					}
					let openPay = (data) => orderInfo({
						orderNumber: data
					}).then(res => {
						this.selectInfo = res
						this.selectVisible = true
					}).catch(() => {
						orderCancel({
							orderNumber: data
						})
					})
					if (this.isClick) return;
					this.isClick = true
					if (![4, 5, 6, 7].includes(goodsType)) {
						orderCreate({
							goodsSpecAttributePriceId,
							...queryObj
						}).then(result => {
							this.isClick = false
							uni.redirectTo({
								url: `/pages/user/order/detail/detail?orderNumber=${ result }`
							})
						}).catch(() => { this.isClick = false })
					} else if ([5, 7].includes(goodsType)) {
						orderCreateCoupon({
							...queryObj
						}).then((data) => {
							this.isClick = false
							openPay(data)
						}).catch(() => { this.isClick = false })
					} else if ([4].includes(goodsType)) {
						if (pinId) {
							queryObj.pinId = pinId
						}
						orderCreate({
							goodsSpecAttributePriceId,
							...queryObj
						}).then(data => {
							this.isClick = false
							openPay(data)
						}).catch(() => { this.isClick = false })
					}
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	.address {
		&-container {
			position: relative;
			top: 0;
			left: 0;
			padding: 0 20rpx;
			height: 166rpx;
			background-color: #FFFFFF;
			border-radius: 16rpx;
		}

		&-line {
			position: absolute;
			left: -20rpx;
			bottom: 0;
		}
	}

	.textarea {
		&-container {
			width: 100%;
			background-color: #F5F5F5;
			border-radius: 4rpx;
		}
	}
</style>
